package com.example.kafka;

import lombok.extern.slf4j.Slf4j;
import org.apache.kafka.clients.producer.ProducerRecord;
import org.springframework.kafka.core.KafkaTemplate;
import org.springframework.kafka.support.SendResult;
import org.springframework.util.concurrent.ListenableFuture;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.PostConstruct;
import javax.annotation.Resource;
import java.util.concurrent.ExecutionException;

/**
 * @Description
 * @Date 2021/6/29
 * @Created by Jonathan
 */
@Slf4j
//@RestController
public class KafkaSyncProducerController {
    @Resource
    private KafkaTemplate<String, String> kafkaTemplate;

    //    @PostConstruct
//    @RequestMapping("send/sync/{message}")
    public void sendSync(String message) {
        ListenableFuture<SendResult<String, String>> ret = kafkaTemplate.send(new ProducerRecord<String, String>("topic_1", 0, "1", message));
        try {
            // 同步等待broker的响应
            SendResult<String, String> result = ret.get();
            log.info("finished");
            log.info(result.getRecordMetadata().topic() + result.getRecordMetadata().partition() + result.getRecordMetadata().offset());
        } catch (InterruptedException | ExecutionException e) {
            log.error("Error:", e.fillInStackTrace());
        }
    }

//    @PostConstruct
    public void main() throws InterruptedException {
        log.info("s");
//        TimeUnit.SECONDS.sleep(10);
        sendSync("hello world");
        log.info("e");
    }

}